<template>
  <div>
    <h2>V2的购物车</h2>
    <div class="table">
      <div class="tr">
        <div class="td">
          <input type="checkbox" v-model="checkedAll" /> 全选
        </div>
        <div class="td">商品名称</div>
        <div class="td">商品价格</div>
        <div class="td">商品数量</div>
        <div class="td">小计</div>
        <div class="td">操作</div>
      </div>

      <div class="tr" v-for="item in list" :key="item.id">
        <div class="td">
          <input type="checkbox" v-model="item.checked" />
        </div>
        <div class="td">{{ item.goodsname }}</div>
        <div class="td">{{ item.goodsprice }}</div>
        <div class="td">
          <button v-show="item.goodsnum > 1" @click="calc(item, -1)">-</button>

          {{ item.goodsnum }}
          <button @click="calc(item, 1)">+</button>
        </div>
        <div class="td">{{ item.goodsnum * item.goodsprice }}</div>
        <div class="td" @click="delListById(item.id)">删除</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    calc(info, num) {
      //info是引用类型  指向同一个内存地址
      info.goodsnum = info.goodsnum + num; //(-  -1   + 1)
    },
    delListById(id) {
      this.list = this.list.filter((item) => item.id != id); //删除
    },
  },
  watch: {
    checkedAll() {
      //监听值类型的变化
      this.list.forEach((item) => {
        //把全选的状态 给集合中的每一个元素s
        item.checked = this.checkedAll;
      });
    },
    //监听 集合的变化
    list: {
      deep: true,
      handler() {
        //深度监听 当集合发生改变的时候也会触发  every 里面的条件都满足 结果才为true  一个不满足结果为false
        this.checkedAll = this.list.every((item) => item.checked);
      },
    },
  },
  data() {
    return {
      checkedAll: false, //全选
      list: [
        {
          id: 1,
          goodsname: "商品名称一",
          goodsprice: 100,
          goodsnum: 10,
          checked: false,
        },
        {
          id: 2,
          goodsname: "商品名称二",
          goodsprice: 200,
          goodsnum: 1,
          checked: false,
        },
        {
          id: 3,
          goodsname: "商品名称三",
          goodsprice: 300,
          goodsnum: 1,
          checked: false,
        },
      ],
    };
  },
};
</script>

<style scoped>
.table {
  width: 100%;
}
.table .tr {
  display: flex;
}
.table .tr .td {
  flex: 1;
  text-align: center;
  line-height: 40px;
  color: gray;
}
</style>
